<?php

class wechatModel extends RPHP_Model
{

    // check wechat user
    public function checkWechatUser($da)
    {
        $code = 407;

        if ($da['headimgurl'] != "") {

            $da['headimgurl'] = str_replace("/132", "/0", str_replace("http://", "https://", $da['headimgurl']));
        }

        $da['sex'] = intval($da['sex']);

        // UNIONID优先
        if ($da['unionid'] != "" && strlen($da['unionid']) > 5) {

            $sql    = "SELECT * FROM {$this->_prefix['primary']}member_wechat WHERE `unionid`='" . $da['unionid'] . "' ORDER BY `wechat_id` DESC LIMIT 1";
            $wechat = $this->db->getrow($sql);

        }

        // 如果UNIONID没有找到，则使用OPENID
        if (!$wechat) {
            $sql    = "SELECT * FROM {$this->_prefix['primary']}member_wechat WHERE `openid`='" . $da['openid'] . "' ORDER BY `wechat_id` DESC LIMIT 1";
            $wechat = $this->db->getrow($sql);
        }

        $da['parent_uid'] = 0;

        if ($_SESSION['qrcode_recode'] != "") {
            $sql    = "SELECT `uid` FROM {$this->_prefix['primary']}member_account WHERE `recode`='" . $_SESSION['qrcode_recode'] . "'";
            $tmpuid = $this->db->getone($sql);
            if ($tmpuid > 0) {
                $da['parent_uid'] = $tmpuid;
            }
        }

        // 更新标志
        $is_update = false;

        // 创建新用户
        if (!$wechat) {
            $this->db->begin();
            $commit = false;
            //
            $sql     = "INSERT INTO {$this->_prefix['primary']}member_account (`realname`,`password`,`pass_rand`,`wechat_headimgurl`,`create_time`,`pid`) VALUES ('" . addslashes($da['nickname']) . "','1','1','" . $da['headimgurl'] . "'," . $_SERVER['REQUEST_TIME'] . "," . $da['parent_uid'] . ")";
            $new_uid = $this->sql($sql);
            if ($new_uid > 0) {
                $sql = "INSERT INTO {$this->_prefix['primary']}member_wechat (`uid`,`openid`,`unionid`,`nickname`,`headimgurl`,`sex`,`create_time`) VALUES (" . $new_uid . ",'" . $da['openid'] . "','" . $da['unionid'] . "','" . addslashes($da['nickname']) . "','" . $da['headimgurl'] . "'," . $da['sex'] . "," . $_SERVER['REQUEST_TIME'] . ")";

                $wechat_id = $this->sql($sql);
                if ($wechat_id > 0) {

                    // 创建资金账户
                    $sql = "INSERT INTO {$this->_prefix['primary']}finance_balance (`uid`) VALUES (" . $new_uid . ")";
                    $rcb = $this->sql($sql);
                    if ($rcb == $new_uid) {

                        $commit = true;

                        $sql    = "SELECT * FROM {$this->_prefix['primary']}member_wechat WHERE `wechat_id`=" . $wechat_id;
                        $wechat = $this->db->getrow($sql);

                    } else {
                        $code = 801;
                    }

                } else {
                    $code = 802;
                }
            } else {
                $code = 803;
            }

            if ($commit) {
                $this->db->commit();
            } else {
                $this->db->rollback();
            }

        }
        // 更新微信资料
        elseif ($wechat['uid'] > 0) {

            $this->db->begin();
            $commit = false;

            // 更新帐户资料
            $sql = "UPDATE {$this->_prefix['primary']}member_account SET `realname`='" . addslashes($da['nickname']) . "',`wechat_headimgurl`='" . $da['headimgurl'] . "',`update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `uid`=" . $wechat['uid'];
            $rcp = $this->sql($sql);
            if ($rcp > 0) {
                // 更新微信资料
                $sql = "UPDATE {$this->_prefix['primary']}member_wechat SET
                `unionid`='" . $da['unionid'] . "',
                `sex`=" . $da['sex'] . ",
                `nickname`='" . addslashes($da['nickname']) . "',
                `headimgurl`='" . $da['headimgurl'] . "',
                `update_time`=" . $_SERVER['REQUEST_TIME'] . " WHERE `wechat_id`=" . $wechat['wechat_id'];
                $rcw = $this->sql($sql);
                if ($rcw > 0) {
                    $commit    = true;
                    $is_update = true;
                }
            }

            if ($commit) {
                $this->db->commit();
            } else {
                $this->db->rollback();
            }
        }

        if ($wechat) {
            if ($wechat['uid'] > 0) {
                $sql  = "SELECT * FROM {$this->_prefix['primary']}member_account WHERE `uid`=" . $wechat['uid'];
                $data = $this->db->getrow($sql);
                if ($data) {
                    if ($data['stat'] == 1) {

                        $this->db->begin();
                        $commit = false;
                        $code   = 403;
                        $appid  = 20001;

                        // 删除之前的登录记录

                        $sql = "DELETE FROM {$this->_prefix['primary']}member_online WHERE `uid`=".$data['uid'];
                        $this->sql($sql);

                        // 插入在线记录
                        $token = md5($data['uid'] . $this->c['secrkey'] . $_SERVER['REQUEST_TIME'] . $_SERVER['REMOTE_ADDR']);

                        $sql = "INSERT INTO {$this->_prefix['primary']}member_online (`uid`,`token`,`signin_time`,`signin_ip`,`appid`,`last_time`) VALUES (" . $data['uid'] . ",'" . $token . "'," . $_SERVER['REQUEST_TIME'] . ",'" . $_SERVER['REMOTE_ADDR'] . "'," . $appid . "," . $_SERVER['REQUEST_TIME'] . ")";

                        $online_id = $this->sql($sql);
                        if ($online_id > 0) {
                            // 插入登录记录
                            $sql        = "INSERT INTO {$this->_prefix['primary']}member_signlog (`uid`,`signin_time`,`signin_ip`,`appid`) VALUES (" . $data['uid'] . "," . $_SERVER['REQUEST_TIME'] . ",'" . $_SERVER['REMOTE_ADDR'] . "'," . $appid . ")";
                            $signlog_id = $this->sql($sql);
                            if ($signlog_id > 0) {
                                // setcookie

                                $value = array(
                                    'uid'          => $data['uid'],
                                    'token'        => $token,
                                    'signin_time'  => $_SERVER['REQUEST_TIME'],
                                    'signin_ip'    => $_SERVER['REMOTE_ADDR'],
                                    'member_level' => $data['member_level'],
                                    'online_id'    => $online_id,
                                    'recode'       => $data['recode'],

                                );

                                // 有效期5个小时
                                $expire = $_SERVER['REQUEST_TIME'] + 18000;
                                if (setcookie($this->c['cookie']['user'], Rfc::encode(serialize($value)), $expire, $this->c['cookie']['path'], $this->c['cookie']['host'])) {

                                    $commit = true;
                                    $code   = 200;

                                } else {
                                    $code = 407;
                                }

                            }

                        }

                        if ($commit) {
                            $this->db->commit();
                        } else {
                            $this->db->rollback();

                        }

                    } else {
                        $code = 405;
                    }

                } else {
                    $code = 404;
                }
            }
        }

        return array('code' => $code);
    }
}
